﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Diagnostics;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;


namespace NGIS
{
    namespace Model
    {
        public enum EModelContextStatus
        {
            EMCS_INIT_BEGIN,
            EMCS_INIT,
            EMCS_INIT_END,

            EMCS_STATE_ENTER_BEGIN,
            EMCS_STATE_ENTER,
            EMCS_STATE_ENTER_END,

            EMCS_EVENT_BEGIN,
            EMCS_EVENT,
            EMCS_EVENT_END,

            EMCS_REQUEST_BEGIN,
            EMCS_REQUEST,
            EMCS_REQUEST_END,

            EMCS_RESPONSE_BEGIN,
            EMCS_RESPONSE,
            EMCS_RESPONSE_END,

            EMCS_POST_BEGIN,
            EMCS_POST,
            EMCS_POST_END,

            EMCS_STATE_LEAVE_BEGIN,
            EMCS_STATE_LEAVE,
            EMCS_STATE_LEAVE_END,

            EMCS_FINALIZE_BEGIN,
            EMCS_FINALIZE,
            EMCS_FINALIZE_END,

            EMCS_COMMON_BEGIN,
            EMCS_COMMON_REQUEST,
            EMCS_COMMON_END,

            EMCS_INIT_CTRLPARAM_BEGIN,
            EMCS_INIT_CTRLPARAM,
            EMCS_INIT_CTRLPARAM_END,

            EMCS_UNKOWN
        };

        public class ModelServiceContext
        {
            private Thread mThreadId;
            private EModelContextStatus mContextStatus;

            private int mPort;
            private string mHost;
            private Guid mInstaceId;
            private string mMappingLibDir; //! 数据映射方法统一安装目录
            private string mInstanceDir; //! 当前模型运行实例的数据目录（以State文件夹组织）

            private Socket mClientSocket;
            private string mSendBuf;
            private string mReceiveBuf;

            private string mReceivedString;

            private string mCurrentState; //! 模型实例运行过程中当前的State
            private string mCurrentEvent; //! 模型实例运行过程中当前的Event

            private ERequestResponseDataFlag mRequestDataFlag;
            private ERequestResponseDataMIME mRequestDataMIME;
            private string mRequestDataBody;

            private ERequestResponseDataFlag mResponseDataFlag;
            private ERequestResponseDataMIME mResponseDataMIME;
            private string mResponseDataBody;

            private string mDebugScriptFile;

            private Dictionary<string, string> mProcessParams;

            private Dictionary<string, object> mControlParams;

            public ModelServiceContext()
            {
                mContextStatus = EModelContextStatus.EMCS_UNKOWN;
                mDebugScriptFile = "";
                this.mProcessParams = new Dictionary<string, string>();
                this.mControlParams = new Dictionary<string, object>();
            }

            //! 触发-初始化
            public Guid onInitialize(string pHost, string pPort, string pInstanceID)
            {
                mHost = pHost;
                mPort = Convert.ToInt32(pPort);
                try
                {
                    mInstaceId = Guid.Parse(pInstanceID);
                }
                catch (System.Exception ex)
                {
                    mInstaceId = Guid.Empty;
                }

                int retVal = bindSocket();
                if (retVal != 0)
                {
                    Console.WriteLine("Init Failed! Cannot Connect Model Service Container");
                    Process.GetCurrentProcess().Kill();
                    return Guid.Empty;
                }

                if (retVal == 0)
                {
                    //! 启动监听线程
                    ParameterizedThreadStart tStart = new ParameterizedThreadStart(ThreadMain);
                    mThreadId = new Thread(tStart);
                    mThreadId.Start(this);
                    if (mThreadId == null)
                    {
                        Console.Write("create thread error\n");
                    }

                    mContextStatus = EModelContextStatus.EMCS_INIT_BEGIN;
                    mContextStatus = EModelContextStatus.EMCS_INIT;
                    mSendBuf = "";
                    mSendBuf = "{init}" + mInstaceId.ToString() + "&" + mDebugScriptFile;
                    sendMessage(mSendBuf);

                    wait(1000, EModelContextStatus.EMCS_INIT_END);

                    int idx = mReceivedString.IndexOf('}');
                    string header = mReceivedString.Substring(0, idx + 1);
                    string body = mReceivedString.Substring(idx + 1, mReceivedString.Length - idx - 1);

                    int idx1 = body.IndexOf('[');
                    int idx2 = body.IndexOf(']');
                    mMappingLibDir = body.Substring(idx1 + 1, idx2 - idx1 - 1);

                    idx1 = body.LastIndexOf('[');
                    idx2 = body.LastIndexOf(']');
                    mInstanceDir = body.Substring(idx1 + 1, idx2 - idx1 - 1);
                }
               
                return mInstaceId;
            }

            //! 触发-进入状态
            public int onEnterState(string pStateId)
            {
                mCurrentState = pStateId;
                this.mContextStatus = EModelContextStatus.EMCS_STATE_ENTER_BEGIN;
                mSendBuf = "";
                mSendBuf = "{onEnterState}" + mInstaceId.ToString() + "&" + pStateId;
                this.mContextStatus = EModelContextStatus.EMCS_STATE_ENTER;
                sendMessage(mSendBuf);

                this.wait(1000, EModelContextStatus.EMCS_STATE_ENTER_END);

                int idx = mReceivedString.IndexOf('}');
                string header = mReceivedString.Substring(0, idx + 1);
                string body = mReceivedString.Substring(idx + 1, mReceivedString.Length - idx - 1);

                header += "\n"; Console.Write(header);
                return 0;
            }

            //! 触发-引发事件
            public int onFireEvent(string pStateId, string pEventId)
            {
                mCurrentEvent = pEventId;
                this.mContextStatus = EModelContextStatus.EMCS_EVENT_BEGIN;
                mSendBuf = "";
                mSendBuf = "{onFireEvent}" + mInstaceId.ToString() + "&" + pStateId + "&" + pEventId;

                this.mContextStatus = EModelContextStatus.EMCS_EVENT;
                sendMessage(mSendBuf);

                this.wait(1000, EModelContextStatus.EMCS_EVENT_END);

                int idx = mReceivedString.IndexOf('}');
                string header = mReceivedString.Substring(0, idx + 1);
                string body = mReceivedString.Substring(idx + 1, mReceivedString.Length - idx - 1);

                header += "\n"; Console.Write(header);
                return 0;
            }

            //! 触发-引发事件
            public int onFireEvent(string pEventId)
            {
                return this.onFireEvent(this.mCurrentState, pEventId);
            }

            //! 触发-向外请求数据
            public int onRequestData(string pStateId, string pEventId)
            {
                resetRequestDataInfo();

                this.mContextStatus = EModelContextStatus.EMCS_REQUEST_BEGIN;
                mSendBuf = "";
                mSendBuf = "{onRequestData}" + mInstaceId.ToString() + "&" + pStateId + "&" + pEventId;

                this.mContextStatus = EModelContextStatus.EMCS_REQUEST;
                sendMessage(mSendBuf);

                this.wait(1000, EModelContextStatus.EMCS_REQUEST_END);

                int idx = mReceivedString.IndexOf('}');
                string header = mReceivedString.Substring(0, idx + 1);
                idx = mReceivedString.LastIndexOf(']');
                string body = mReceivedString.Substring(idx + 1, mReceivedString.Length - idx - 1);

                Console.Write(header);

                //////////////////////////////////////////////////////////////////////////
                int idx1 = mReceivedString.IndexOf('[');
                int idx2 = mReceivedString.IndexOf(']');
                string data_flag = mReceivedString.Substring(idx1 + 1, idx2 - idx1 - 1);

                if (data_flag == "OK")
                {
                    mRequestDataFlag = ERequestResponseDataFlag.ERDF_OK;
                    Console.Write("[OK]\n");
                }
                else
                {
                    mRequestDataMIME = ERequestResponseDataMIME.ERDM_UNKNOW;
                    mRequestDataBody = "";
                    Console.Write("[ERROR]\n");
                    return 0;
                }

                idx1 = mReceivedString.LastIndexOf('[');
                idx2 = mReceivedString.LastIndexOf(']');
                string data_mime = mReceivedString.Substring(idx1 + 1, idx2 - idx1 - 1);

                if (data_mime == "XML|STREAM")
                {
                    mRequestDataMIME = ERequestResponseDataMIME.ERDM_XML_STREAM;
                }
                else if (data_mime == "ZIP|STREAM")
                {
                    mRequestDataMIME = ERequestResponseDataMIME.ERDM_ZIP_STREAM;
                }
                else if (data_mime == "RAW|STREAM")
                {
                    mRequestDataMIME = ERequestResponseDataMIME.ERDM_RAW_STREAM;
                }
                else if (data_mime == "XML|FILE")
                {
                    mRequestDataMIME = ERequestResponseDataMIME.ERDM_XML_FILE;
                }
                else if (data_mime == "ZIP|FILE")
                {
                    mRequestDataMIME = ERequestResponseDataMIME.ERDM_ZIP_FILE;
                }
                else if (data_mime == "RAW|FILE")
                {
                    mRequestDataMIME = ERequestResponseDataMIME.ERDM_RAW_FILE;
                }

                mRequestDataBody = body;

                return 0;
            }

            //! 触发-向外请求数据
            public int onRequestData()
            {
                return this.onRequestData(this.mCurrentState, this.mCurrentEvent);
            }

            //! 触发-向外提供数据
            public int onResponseData(string pStateId, string pEventId)
            {
                if (mResponseDataFlag == ERequestResponseDataFlag.ERDF_OK)
                {
                    this.mContextStatus = EModelContextStatus.EMCS_RESPONSE_BEGIN;
                    int size = mResponseDataBody.Length;
                    mSendBuf = "";
                    mSendBuf = "{onResponseData}" + mInstaceId.ToString() + "&" + pStateId + "&" + pEventId + "&" + size.ToString() + "[OK]";

                    string sendBufStr = mSendBuf;

                    if (mResponseDataMIME == ERequestResponseDataMIME.ERDM_XML_STREAM)
                    {
                        sendBufStr += "[XML|STREAM]";
                    }
                    else if (mResponseDataMIME == ERequestResponseDataMIME.ERDM_ZIP_STREAM)
                    {
                        sendBufStr += "[ZIP|STREAM]";
                    }
                    else if (mResponseDataMIME == ERequestResponseDataMIME.ERDM_RAW_STREAM)
                    {
                        sendBufStr += "[RAW|STREAM]";
                    }
                    else if (mResponseDataMIME == ERequestResponseDataMIME.ERDM_XML_FILE)
                    {
                        sendBufStr += "[XML|FILE]";
                    }
                    else if (mResponseDataMIME == ERequestResponseDataMIME.ERDM_ZIP_FILE)
                    {
                        sendBufStr += "[ZIP|FILE]";
                    }
                    else if (mResponseDataMIME == ERequestResponseDataMIME.ERDM_RAW_FILE)
                    {
                        sendBufStr += "[RAW|FILE]";
                    }
                    sendBufStr += mResponseDataBody;
                    this.mContextStatus = EModelContextStatus.EMCS_RESPONSE;
                    sendMessage(sendBufStr);

                    this.wait(1000, EModelContextStatus.EMCS_RESPONSE_END);

                    mReceivedString += "\n"; Console.Write(mReceivedString);
                }
                else if (mResponseDataFlag == ERequestResponseDataFlag.ERDF_ERROR)
                {
                    this.mContextStatus = EModelContextStatus.EMCS_RESPONSE_BEGIN;
                    mSendBuf = "";
                    mSendBuf = "{onResponseData}" + mInstaceId.ToString() + "&" + pStateId + "&" + pEventId + "&0" + "[ERROR]";

                    this.mContextStatus = EModelContextStatus.EMCS_RESPONSE;
                    sendMessage(mSendBuf);

                    this.wait(1000, EModelContextStatus.EMCS_RESPONSE_END);

                    int idx = mReceivedString.IndexOf('}');
                    string header = mReceivedString.Substring(0, idx + 1);
                    string body = mReceivedString.Substring(idx + 1, mReceivedString.Length - idx - 1);

                    header += "\n"; Console.Write(header);
                }
                else if (mResponseDataFlag == ERequestResponseDataFlag.ERDF_NOTREADY)
                {
                    this.mContextStatus = EModelContextStatus.EMCS_RESPONSE_BEGIN;
                    int size = mResponseDataBody.Length;
                    mSendBuf = "";
                    mSendBuf = "{onResponseData}" + mInstaceId.ToString() + "&" + pStateId + "&" + pEventId + "&" + size.ToString() + "[NOTREADY]";

                    this.mContextStatus = EModelContextStatus.EMCS_RESPONSE;
                    sendMessage(mSendBuf);

                    this.wait(1000, EModelContextStatus.EMCS_RESPONSE_END);

                    int idx = mReceivedString.IndexOf('}');
                    string header = mReceivedString.Substring(0, idx + 1);
                    string body = mReceivedString.Substring(idx + 1, mReceivedString.Length - idx - 1);

                    header += "\n"; Console.Write(header);
                }

                resetResponseDataInfo();
                return 0;
            }
            
            //! 触发-向外提供数据
            public int onResponseData()
            {
                return this.onRequestData(this.mCurrentState, this.mCurrentEvent);
            }

            //! 触发-提交错误信息
            public int onPostErrorInfo(string errorInfo)
            {
                this.mContextStatus = EModelContextStatus.EMCS_POST_BEGIN;
                mSendBuf = "";
                mSendBuf = "{onPostErrorInfo}" + mInstaceId.ToString() + "&" + errorInfo;
                this.mContextStatus = EModelContextStatus.EMCS_POST;
                sendMessage(mSendBuf);

                this.wait(1000, EModelContextStatus.EMCS_POST_END);

                int idx = mReceivedString.IndexOf('}');
                string header = mReceivedString.Substring(0, idx + 1);
                string body = mReceivedString.Substring(idx + 1, mReceivedString.Length - idx - 1);

                header += "\n"; Console.Write(header);

                return 0;
            }

            //! 触发-提交警告信息
            public int onPostWarningInfo(string waringInfo)
            {
                this.mContextStatus = EModelContextStatus.EMCS_POST_BEGIN;
                mSendBuf = "";
                mSendBuf = "{onPostWarningInfo}" + mInstaceId.ToString() + "&" + waringInfo;
                this.mContextStatus = EModelContextStatus.EMCS_POST;
                sendMessage(mSendBuf);

                this.wait(1000, EModelContextStatus.EMCS_POST_END);

                int idx = mReceivedString.IndexOf('}');
                string header = mReceivedString.Substring(0, idx + 1);
                string body = mReceivedString.Substring(idx + 1, mReceivedString.Length - idx - 1);

                header += "\n"; Console.Write(header);

                return 0;
            }

            //! 触发-提交提示信息
            public int onPostMessageInfo(string messageInfo)
            {
                this.mContextStatus = EModelContextStatus.EMCS_POST_BEGIN;
                mSendBuf = "";
                mSendBuf = "{onPostMessageInfo}" + mInstaceId.ToString() + "&" + messageInfo;
                this.mContextStatus = EModelContextStatus.EMCS_POST;
                sendMessage(mSendBuf);

                this.wait(1000, EModelContextStatus.EMCS_POST_END);

                int idx = mReceivedString.IndexOf('}');
                string header = mReceivedString.Substring(0, idx + 1);
                string body = mReceivedString.Substring(idx + 1, mReceivedString.Length - idx - 1);

                header += "\n"; Console.Write(header);

                return 0;
            }

            //! 触发-离开状态
            public int onLeaveState(string pStateId)
            {
                this.mContextStatus = EModelContextStatus.EMCS_STATE_LEAVE_BEGIN;
                mSendBuf = "";
                mSendBuf = "{onLeaveState}" + mInstaceId.ToString() + "&" + pStateId;
                this.mContextStatus = EModelContextStatus.EMCS_STATE_LEAVE;
                sendMessage(mSendBuf);

                this.wait(1000, EModelContextStatus.EMCS_STATE_LEAVE_END);

                int idx = mReceivedString.IndexOf('}');
                string header = mReceivedString.Substring(0, idx + 1);
                string body = mReceivedString.Substring(idx + 1, mReceivedString.Length - idx - 1);

                header += "\n"; Console.Write(header);

                return 0;
            }

            //! 触发-离开状态
            public int onLeaveState()
            {
                return this.onLeaveState(this.mCurrentState);
            }

            //! 触发-完成
            public int onFinalize()
            {
                this.mContextStatus = EModelContextStatus.EMCS_FINALIZE_BEGIN;
                mSendBuf = "";
                mSendBuf = "{onFinalize}" + mInstaceId.ToString();
                this.mContextStatus = EModelContextStatus.EMCS_FINALIZE;
                sendMessage(mSendBuf);

                this.wait(1000, EModelContextStatus.EMCS_FINALIZE_END);

                int idx = mReceivedString.IndexOf('}');
                string header = mReceivedString.Substring(0, idx + 1);
                string body = mReceivedString.Substring(idx + 1, mReceivedString.Length - idx - 1);

                header += "\n"; Console.Write(header);

                mThreadId.Abort();
                closeSocket();

                Process.GetCurrentProcess().Kill();
                return 0;
            }

            //! 触发-获取数据映射方法路径事件
            public string onGetModelAssembly(string pMethodName)
            {
                this.mContextStatus = EModelContextStatus.EMCS_COMMON_BEGIN;
                mSendBuf = "";
                mSendBuf = "{onGetModelAssembly}" + mInstaceId.ToString() + "&" + pMethodName;            
                this.mContextStatus = EModelContextStatus.EMCS_COMMON_REQUEST;
                sendMessage(mSendBuf);

                this.wait(1000, EModelContextStatus.EMCS_COMMON_END);

                int idx = mReceivedString.IndexOf('}');
                string header = mReceivedString.Substring(0, idx + 1);
                string body = mReceivedString.Substring(idx + 1, mReceivedString.Length - idx - 1);

                header += "\n"; Console.Write(header);
                Console.WriteLine("ModelAssembly: " + body);

                return body;
            }

            //////////////////////////////////////////////////////////////////////////
            //! 请求到的数据Flag
            public ERequestResponseDataFlag getRequestDataFlag()
            {
                return mRequestDataFlag;
            }

            //! 请求到的数据类型
            public ERequestResponseDataMIME getRequestDataMIME()
            {
                return mRequestDataMIME;
            }

            //! 请求到的数据内容
            public string getRequestDataBody()
            {
                return mRequestDataBody;
            }

            //! 发送的数据标记Flag
            public void setResponseDataFlag(ERequestResponseDataFlag pFlag)
            {
                mResponseDataFlag = pFlag;
            }

            //! 发送的数据MIME类型
            public void setResponseDataMIME(ERequestResponseDataMIME pMIME)
            {
                mResponseDataMIME = pMIME;
            }

            //! 发送的数据内容
            public void setResponseDataBody(string pDataBody)
            {
                mResponseDataBody = pDataBody;
            }

            //! 发送出去的数据Flag
            public ERequestResponseDataFlag getResponseDataFlag()
            {
                return mResponseDataFlag;
            }

            //! 发送出去的数据MIME
            public ERequestResponseDataMIME getResponseDataMIME()
            {
                return mResponseDataMIME;
            }

            //! 发送出去的数据内容
            public string getResponseDataBody()
            {
                return mResponseDataBody;
            }

            //! 获取当前与外部通信的状态
            public EModelContextStatus getCurrentStatus()
            {
                return mContextStatus;
            }

            //////////////////////////////////////////////////////////////////////////
            //! 获取当前的数据目录
            public string getCurrentDataDirectory()
            {
                string instanceDir = getModelInstanceDirectory();
                if (Directory.Exists(instanceDir) == false)
                {
                    Directory.CreateDirectory(instanceDir);
                }

                string stateDir = getCurrentRunningState() + "\\";
                string eventDir = getCurrentRunningEvent() + "\\";

                string statePath = instanceDir + stateDir;
                if (Directory.Exists(statePath) == false)
                {
                    Directory.CreateDirectory(statePath);
                }

                string eventPath = statePath + eventDir;
                if (Directory.Exists(eventPath) == false)
                {
                    Directory.CreateDirectory(eventPath);
                }

                return eventPath;
            }

            //! 获取数据映射方法的CommonShell目录
            public string getMappingLibraryDirectory()
            {
                if (mMappingLibDir.LastIndexOf('\\') != mMappingLibDir.Length - 1)
                {
                    mMappingLibDir += "\\";
                }
                return mMappingLibDir;
            }

            //! 获取模型运行实例的工作目录
            public string getModelInstanceDirectory()
            {
                if (mInstanceDir.LastIndexOf('\\') != mInstanceDir.Length - 1)
                {
                    mInstanceDir += "\\";
                }
                return mInstanceDir;
            }

            //! 获取模型运行实例当前的State
            public string getCurrentRunningState() { return mCurrentState; }

            //! 获取模型运行实例当前的Event
            public string getCurrentRunningEvent() { return mCurrentEvent; }

            //! 获取过程变量
            public string getProcessParam(string key)
            {
                if (this.mProcessParams.ContainsKey(key))
                {
                    return this.mProcessParams[key];
                }
                return "";
            }

            //! 设置过程变量
            public void setProcessParam(string key, string value)
            {
                this.mProcessParams[key] = value;
                this.sendProcessParams();
            }

            //! 设置过程变量
            public void setProcessParam(string key, double value)
            {
                this.mProcessParams[key] = value.ToString();
                this.sendProcessParams();
            }

            //! 初始化控制变量
            public int initControlParam()
            {
                this.mContextStatus = EModelContextStatus.EMCS_INIT_CTRLPARAM_BEGIN;
                this.mSendBuf = "";
                this.mSendBuf = "{onInitControlParam}" + this.mInstaceId.ToString();

                sendMessage(mSendBuf);
                this.mContextStatus = EModelContextStatus.EMCS_INIT_CTRLPARAM;

                this.wait(1000, EModelContextStatus.EMCS_INIT_CTRLPARAM_END);

                int idx = mReceivedString.IndexOf('}');
                string header = mReceivedString.Substring(0, idx + 1);
                string body = mReceivedString.Substring(idx + 1, mReceivedString.Length - idx - 1);

                this.setControlParams(body);

                header += "\n"; Console.Write(header);
                return 1;
            }

            //! 获取控制变量
            public string getControlParam(string key)
            {
                if (this.mControlParams.ContainsKey(key))
                {
                    return this.mControlParams[key].ToString();
                }
                return "";
            }


            //////////////////////////////////////////////////////////////////////////
            //! 启动一个新的外部进程
            public bool startANewProcess(string cmd, string workingPath)
            {
                try
                {
                    Process pProcess = new Process();
                    pProcess.StartInfo.FileName = "cmd.exe";
                    pProcess.StartInfo.Arguments = "/c \"" + cmd + "\"";
                    pProcess.StartInfo.UseShellExecute = false;
                    pProcess.StartInfo.RedirectStandardInput = false;
                    pProcess.StartInfo.RedirectStandardOutput = false;
                    pProcess.StartInfo.RedirectStandardError = false;
                    pProcess.StartInfo.CreateNoWindow = true;
                    pProcess.Start();

                    pProcess.WaitForExit();

                    return true;
                }
                catch (System.Exception ex)
                {
                    return false;
                }
            }

            //! 设置模型实例的Debug脚本
            public void setModelInstanceDebugScript(string pScriptFile)
            {
                mDebugScriptFile = pScriptFile;
            }

            //////////////////////////////////////////////////////////////////////////
            //
            //
            //
            //////////////////////////////////////////////////////////////////////////
            private int bindSocket()
            {
                IPAddress ip = IPAddress.Parse(mHost);
                IPEndPoint ipe = new IPEndPoint(ip, mPort);

                mClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                try
                {
                    mClientSocket.Connect(ipe);
                }
                catch (System.Exception ex)
                {
                    return -1;
                }
                return 0;
            }

            private int sendMessage(string pMessage)
            {
                pMessage += '\0';
                byte[] sendBytes = Encoding.Default.GetBytes(pMessage);
                try
                {
                    mClientSocket.Send(sendBytes, sendBytes.Length, SocketFlags.None);
                }
                catch (System.Exception ex)
                {
                    return -1;
                }
                return 0;
            }

            private int receiveMessage(ref string pMessage)
            {
                byte[] recBytes = new byte[4096];
                try
                {
                    int bytes = mClientSocket.Receive(recBytes, recBytes.Length, 0);
                    pMessage += Encoding.Default.GetString(recBytes, 0, bytes);
                }
                catch (System.Exception ex)
                {
                    return -1;
                }
                return 0;
            }

            private void closeSocket()
            {
                mClientSocket.Close();
            }

            private void wait(int seconds, EModelContextStatus pStatus)
            {
                while (true)
                {
                    if (mContextStatus == pStatus)
                    {
                        break;
                    }
                    Thread.Sleep(10);
                }
            }

            private void setCurrentContextStatus(EModelContextStatus pStatus)
            {
                mContextStatus = pStatus;
            }

            private void setCurrentReceivedInfo(string pInfo)
            {
                mReceivedString = pInfo;
            }

            private void resetRequestDataInfo()
            {
                this.mRequestDataFlag = ERequestResponseDataFlag.ERDF_UNKNOW;
                this.mRequestDataMIME = ERequestResponseDataMIME.ERDM_UNKNOW;
            }

            private void resetResponseDataInfo()
            {
                this.mResponseDataFlag = ERequestResponseDataFlag.ERDF_UNKNOW;
                this.mResponseDataMIME = ERequestResponseDataMIME.ERDM_UNKNOW;
            }

            private void sendProcessParams()
            {
                string message = "{ProcessParams}" + this.mInstaceId + "&";
                message += (new JavaScriptSerializer()).Serialize(this.mProcessParams);
                this.sendMessage(message);
            }

            private void setControlParams(string paramsBuffer)
            {
                try
                {
                    this.mControlParams = (Dictionary<string, object>)(new JavaScriptSerializer()).DeserializeObject(paramsBuffer);
                }
                catch(Exception ex)
                {

                }
            }

            private static void ThreadMain(object pContext)
            {
                ModelServiceContext realContext = (ModelServiceContext)pContext;

                while (true)
                {
                    string receiveBuf = "";
                    int i = realContext.receiveMessage(ref receiveBuf);
                    if (i < 0) continue;

                    Console.Write("********\n"); Console.Write(receiveBuf); Console.Write("\n*********\n");

                    string[] strCmds = receiveBuf.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);

                    for (int index = 0; index < strCmds.Length; index++)
                    {
                        realContext.setCurrentReceivedInfo(strCmds[index]);
                        int idx = strCmds[index].IndexOf('}');
                        string header = strCmds[index].Substring(0, idx + 1);
                        if (header == "{Initialized}")
                        {
                            realContext.setCurrentContextStatus(EModelContextStatus.EMCS_INIT_END);
                        }
                        else if (header == "{Enter State Notified}")
                        {
                            realContext.setCurrentContextStatus(EModelContextStatus.EMCS_STATE_ENTER_END);
                        }
                        else if (header == "{Fire Event Notified}")
                        {
                            realContext.setCurrentContextStatus(EModelContextStatus.EMCS_EVENT_END);
                        }
                        else if (header == "{Request Data Notified}")
                        {
                            realContext.setCurrentContextStatus(EModelContextStatus.EMCS_REQUEST_END);
                        }
                        else if (header == "{Response Data Notified}")
                        {
                            realContext.setCurrentContextStatus(EModelContextStatus.EMCS_RESPONSE_END);
                        }
                        else if (header == "{Response Data Received}")
                        {
                            realContext.setCurrentContextStatus(EModelContextStatus.EMCS_RESPONSE_END);
                        }
                        else if (header == "{Post Error Info Notified}")
                        {
                            realContext.setCurrentContextStatus(EModelContextStatus.EMCS_POST_END);
                        }
                        else if (header == "{Post Warning Info Notified}")
                        {
                            realContext.setCurrentContextStatus(EModelContextStatus.EMCS_POST_END);
                        }
                        else if (header == "{Post Message Info Notified}")
                        {
                            realContext.setCurrentContextStatus(EModelContextStatus.EMCS_POST_END);
                        }
                        else if (header == "{Leave State Notified}")
                        {
                            realContext.setCurrentContextStatus(EModelContextStatus.EMCS_STATE_LEAVE_END);
                        }
                        else if (header == "{Finalize Notified}")
                        {
                            realContext.setCurrentContextStatus(EModelContextStatus.EMCS_FINALIZE_END);
                            break;
                        }
                        else if (header == "{GetModelAssembly Notified}")
                        {
                            realContext.setCurrentContextStatus(EModelContextStatus.EMCS_COMMON_END);
                        }
                        else if (header == "{InitControlParams Notified}")
                        {
                            realContext.setCurrentContextStatus(EModelContextStatus.EMCS_INIT_CTRLPARAM_END);
                        }

                        if (header == "{kill}")
                        {
                            Process current = Process.GetCurrentProcess();
                            current.Kill();
                        }
                        Thread.Sleep(1000);
                    }
                }
            }
        }

    }
}
